﻿using Furion;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Furion.Core
{
    public class AuthorizationManager:IAuthorizationManager,ITransient
    {
        private readonly IRepository<User> _userRepository;
        private readonly IHttpContextAccessor _httpContextAccessor;


        public AuthorizationManager(IRepository<User> userRepository, IHttpContextAccessor httpContextAccessor)
        {
            _userRepository = userRepository;
            _httpContextAccessor = httpContextAccessor;
        }

        

        /// <summary>
        /// 登录状态是否有效
        /// </summary>
        public bool IsAuthenticated
        {
            get => _httpContextAccessor.HttpContext.User != null ? _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated : false;
        }


        public long UserId
        {
            get => IsAuthenticated ? long.Parse(_httpContextAccessor.HttpContext.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value) : 0;
        }


        public string Name
        {
            get => IsAuthenticated ? _httpContextAccessor.HttpContext.User.FindFirst(ClaimConst.CLAINM_NAME)?.Value:"";
        }


        public User User
        {
            get => _userRepository.FirstOrDefault(u => u.Id == UserId, false);
        }



        public bool CheckPermisionn(string resourceId)
        {
            

            //-------------------------缓存------------------------------
            var permissions = _userRepository.Include(u => u.Roles, false)
                .ThenInclude(u => u.Permissions)
                .Where(u => u.Id == UserId)
                .SelectMany(u => u.Roles
                    .SelectMany(u => u.Permissions))
                .Select(u => u.PermissionCode)
                .Distinct();

            if(!permissions.Contains(resourceId))
            {
                return false;
            }
            return true;
        }



      

    }
}
